/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Form, Table, Tabs} from 'antd';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import DescGroup from "../../../components/DescriptionGroup";
import ViewTitle from "../../../components/ViewTitle";
import notify from "../../../components/NotificationExtra";
import styles from "../../index.less";
import {ModalView} from "antd-extra";
import ModalProdDetail from "./ModalProdDetail";
import ModalOutboundLotDetail from "../../store/modal/ModalOutboundLotDetail";
import MaterialElement from "../../finance/modal/MaterialElement";
import ModalShippedFromManufacturer from "./ModalShippedFromManufacturer";
import SalesBase from "../SalesBase";

const {TabPane} = Tabs;
moment.locale('zh-cn');
const table = 'SalesOrder';
@Form.create()
@connect(({
            user,
            global,
            dynamicLabel,
            sales,
            finance,
            store
          }) => ({...user, ...finance, ...store, ...sales, ...dynamicLabel, ...global}))
export default class ModalSalesOrderDetail extends SalesBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {values, dispatch, treeId} = this.props;

    const {code} = values;
    dispatch && dispatch({
      type: 'sales/findOne',
      payload: {code}
    });
    // if (isReview) return;

    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table}
    });
    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table: 'OutboundOrder'}
    });
    this.props.dispatch({
      type: 'finance/findRecordMany',
      payload: {orderCode: code, table: 'Receipt', treeId: treeId}
    });
    this.props.dispatch({
      type: 'sales/findReplenishRecordMany',
      payload: {salesOrderCode: code}
    });
    this.props.dispatch({
      type: 'sales/findReturnOrderMany',
      payload: {salesOrderCode: code}
    });
    this.props.dispatch({
      type: 'store/findOutboundLots',
      payload: {salesOrderCode: code}
    });

  }


  replenishRecordCol() {

    return [
      {
        title: "品名编号", dataIndex: 'prodName', key: 'prodName', fixed: 'left', render: (value, record) => {
          const {prodCode} = record;
          return this.getProductionElement(prodCode, value);
        }
      },
      {title: "品名", key: "prodName", dataIndex: "prodName"},
      {title: "编号", key: "prodCode", dataIndex: "prodCode"},
      {title: "数量", key: "count", dataIndex: "count"},
      {title: "单价", key: "price", dataIndex: "price"},
      {title: "标签", key: "label", dataIndex: "label"},
      {title: "发货方式", key: "deliverWay", dataIndex: "deliverWay"},
      {title: "包装", key: "pkg", dataIndex: "pkg"},
      {title: "包装费用", key: "pkgFee", dataIndex: "pkgFee"}];
  }

  prodTableCol() {
    const {isFinance = false, isPayReview} = this.props;
    return [
      {
        title: "品名编号", dataIndex: 'prodName', key: 'prodName', render: (value, record) => {
          const {prodCode} = record;
          return this.getProductionElement(prodCode, value);
        }
      },
      {title: "品名", key: "prodName", dataIndex: "prodName"},
      {title: "编号", key: "prodCode", dataIndex: "prodCode"},
      {title: "数量", key: "count", dataIndex: "count"},
      {title: "单价", key: "price", dataIndex: "price"},
      {
        title: "总价", key: "price", dataIndex: "price", render: (value, record) => {
          const {price, count} = record;
          return <div>{price * count}</div>;
        }
      },
      {title: "标签", key: "label", dataIndex: "label"},
      {title: "发货方式", key: "deliverWay", dataIndex: "deliverWay"},
      {title: "包装", key: "pkg", dataIndex: "pkg"},
      {title: "包装费用", key: "pkgFee", dataIndex: "pkgFee"},
      {
        title: "出货数量", key: "outboundCount", dataIndex: "outboundCount", render: (value, record) => {
          const {outboundLots = []} = this.props;
          const {spLotId} = record;
          let count = 0;
          _.map(outboundLots, lot => {
            const {outboundCount} = lot;
            if (spLotId === lot.spLotId) {
              count += outboundCount;
            }
          });
          return <div>{count}</div>;
        }
      },
      {title: "项目奖励", key: "laborFee", dataIndex: "laborFee"},
      {title: "劳务扣税金额", key: "taxDeductionPointForLaborCosts", dataIndex: "taxDeductionPointForLaborCosts"},
      {
        title: "操作", key: 'opt', dataIndex: "opt", fixed: 'right', render: (value, record) => {
          const {materialLots = []} = record;
          return <span>
            <a style={{marginRight: '6px'}} onClick={() => {
              ModalView.open(ModalProdDetail, {
                title: '商品详情',
                width: '1580px'
              }, {
                values: record,
                callback: data => {

                }
              });
            }}>详情</a>
            {<a disabled={record.deliverWay !== '厂家直发' || !materialLots.length} style={{marginRight: '6px'}}
                onClick={() => {

                  ModalView.open(ModalShippedFromManufacturer, {
                    title: '厂家直发出入库批次信息确认',
                    width: '1280px'
                  }, {
                    record,
                    callback: payload => {
                      this.props.dispatch({
                        type: 'store/createOutboundLot',
                        payload
                      }).then(res => {
                        this.requestReturn(res);
                        this.componentDidMount();
                      });
                    }
                  });
                }}>一键出货</a>
            }
          </span>;
        }
      }
    ];
  }

  lotCols() {
    const model = this.props['OutboundOrderModel'];

    const temp = this.getOutboundLotCols(model);
    temp.push(
      {
        title: '操作', key: 'opt', dataIndex: "opt", render: (value, values) => {
          return <a onClick={() => {
            ModalView.open(ModalOutboundLotDetail, {
              title: '出库记录详情',
              width: '920px',
              maskClosable: false
            }, {
              values,
              callback: (result) => {
                const {lotCode} = values;
                const {shippingFee = 0} = result;

                this.props.dispatch({
                  type: 'store/updateShippingFee',
                  payload: {shippingFee, lotCode}
                }).then(response => {
                  this.requestReturn(response);
                  this.componentDidMount();
                });
              }
            });
          }} style={{marginRight: '6px'}}>详情</a>;
        }
      }
    );
    return temp;
  }

  returnGoodsCols() {
    return [
      {
        title: '商品', dataIndex: 'prodName', key: 'prodName', render: (value, record) => {
          const {prodCode, prodName} = record;
          return <MaterialElement name={prodName} code={prodCode}></MaterialElement>;
        }
      },
      {title: '退货数量', dataIndex: 'returnCount', key: 'returnCount'}

    ];
  }


  render() {
    const {
      style,
      salesOrder = {},
      isReview = false,
      isPayReview = false,
      reviewPath, outboundLots = [],
      cols = 4, returnGoods = {}, replenishRecords = {}
    } = this.props;
    const {_notify} = this.state;
    let _shippingFee = 0;

    _.map(outboundLots, lot => {
      const {shippingFee = 0} = lot;
      _shippingFee += shippingFee;
    });
    if (_notify) {
      notify(_notify);
    }

    const model = this.props[`${table}Model`];
    if (!model || !salesOrder) return <div></div>;
    const _labels = _.filter(model, (item, key) => {
      if (key !== 'labels' && _.includes(item.enableArea, 'detail')) {
        item.key = key;
        return item;
      }
    });

    const _values = _.cloneDeep(salesOrder);
    _values.shippingFee = _shippingFee;
    _.map(_labels, item => {
      const {_type, key} = item;
      if (_type.toLowerCase() === 'switch') {
        _values[key] = _values[key] ? "是" : "否";
      }
      if (_type.toLowerCase() === 'date') {
        _values[key] = _values[key] ? moment(_values[key]).format('YYYY-MM-DD') : '';
      }
    });

    const loginInfo = wStore.getStore('loginInfo');
    const createUser = loginInfo ? loginInfo.username : undefined;
    const createUsername = loginInfo ? loginInfo.nickname : undefined;
    const {code, reviewStatus} = salesOrder;
    return (
      <div style={{...style}}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="订单" key="1">
            <ViewTitle
              title={'订单信息'}
              level={1}
              actions={[
                isReview && <Button type="primary" disabled={reviewStatus === '同意'} onClick={() => {

                  isReview && this.props.dispatch({
                    type: 'sales/review',
                    payload: {code, reviewStatus: '同意'}
                  }).then(res => {
                    this.componentDidMount();
                  });


                }}>同意</Button>,
                (isPayReview || isReview) && <Button type={'danger'} disabled={reviewStatus === '驳回'} onClick={() => {

                  this.props.dispatch({
                    type: 'sales/review',
                    payload: {code, reviewStatus: '驳回', createUser, createUsername}
                  }).then(res => {
                    this.componentDidMount();
                  });

                  isReview && this.props.dispatch({
                    type: 'sales/review',
                    payload: {code, reviewStatus: '驳回'}
                  }).then(res => {
                    this.componentDidMount();
                  });
                  const _payload = {code};
                  _payload[reviewPath] = "驳回";
                  isPayReview && this.props.dispatch({
                    type: 'sales/review',
                    payload: _payload
                  }).then(res => {
                    this.componentDidMount();
                  });
                }}>驳回</Button>
              ]}
            ></ViewTitle>
            <DescGroup
              {...{
                labels: _labels,
                values: _values,
                size: 'small',
                column: cols
              }}
            ></DescGroup>

            <ViewTitle
              title={'商品信息'}
            ></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.prodTableCol()}
              dataSource={salesOrder.prods}
              scroll={{x: true}}
              pagination={true}
            ></Table>
          </TabPane>
          <TabPane tab={'出货'} key="2">
            {<ViewTitle
              title={'出库单信息'}
              level={1}
            ></ViewTitle>}
            {
              <Table
                className={styles.antTable}
                bordered={true}
                columns={this.lotCols()}
                dataSource={outboundLots}
                scroll={{x: true}}
                pagination={true}
              ></Table>
            }
          </TabPane>
          <TabPane tab={'退补货'} key="3">
            {<ViewTitle
              title={'商品退货列表'}
              level={1}
            ></ViewTitle>}
            {
              <Table
                className={styles.antTable}
                bordered={true}
                columns={this.returnGoodsCols()}
                dataSource={returnGoods.list}
                scroll={{x: true}}
                pagination={true}
              ></Table>
            }
            {<ViewTitle
              title={'商品补货列表'}
              level={1}
            ></ViewTitle>}
            {
              <Table
                className={styles.antTable}
                bordered={true}
                columns={this.replenishRecordCol()}
                dataSource={replenishRecords.list}
                scroll={{x: true}}
                pagination={true}
              ></Table>
            }
          </TabPane>
        </Tabs>
      </div>
    );
  }
}

